using AlibabaCloud.SDK.Sts20150401.Models;
using log4net;
using Mathmall.Administration.common;
using Mathmall.Administration.Config;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;

namespace Mathmall.Administration.oss;

[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
    private static readonly ILog _logger = LogManager.GetLogger(typeof(FileController));

    private readonly UploadOptions _uploadOptions;

    public FileController(IOptionsSnapshot<UploadOptions> uploadOptions)
    {
        _uploadOptions = uploadOptions.Value;
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<ActionResult<string>> OnPostUploadAsync(IFormFile file)
    {
        // 校验图片格式
        string[] permittedExtensions = [".jpg", ".png", ".gif", ".jpeg"];
        string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (string.IsNullOrEmpty(fileExtension) || !permittedExtensions.Contains(fileExtension))
        {
            return BadRequest();
        }

        // 校验图片大小
        if (file.Length > _uploadOptions.ImgSize)
        {
            return BadRequest();
        }

        // 获取文件扩展名
        var fileName = Path.GetRandomFileName().Replace(".", "") + Path.GetExtension(file.FileName);

        // 获取文件保存路径
        var filePath = Path.Combine(_uploadOptions.ImgPath, fileName);
        using (var stream = System.IO.File.Create(filePath))
        {
            await file.CopyToAsync(stream);
        }

        return _uploadOptions.ImgPathPrefix + fileName;
    }

    /// <summary>
    /// 获取签名
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public R<Dictionary<string, object>> GetSignature()
    {
        var oss = new Oss();
        _logger.Debug("Getting signature");
        return new R<Dictionary<string, object>>().Success(oss.GetPostSignatureForOssUpload());
    }

    /// <summary>
    /// 获取STS token
    /// </summary>
    /// <returns></returns>
    [HttpPost("[action]")]
    public ActionResult<AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials> GetCredential()
    {
        var oss = new Oss();
        return oss.GetSTSToeknForOssUpload();
    }
}